package com.example.softwarearchitectureexamples.interceptor;

import com.example.softwarearchitectureexamples.exception.XException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

//拦截器，拦截未登录
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //通过token判断是否登录
        if(request.getHeader("uid") == null && request.getHeader("role") == null) {
            throw new XException("未登录");
        }

        //正常情况下这里的token是加密的，这里进行解密后再获取uid和role
        int uid = Integer.parseInt(request.getHeader("uid"));
        int role = Integer.parseInt(request.getHeader("role"));

        request.setAttribute("role", role);
        request.setAttribute("uid", uid);

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
